<template>
  <div class="container flex-box between"  style="align-items: flex-start;">

	  <div class="fl wareList"  >
    <div v-if="!activeMode" class="modeBtn">
      <el-button class="marBtm" @click="onClickMode('ONLINE')">在线word文档模式</el-button>
      <el-button @click="onClickMode('MODULE')">标准模式</el-button>
    </div>

    <el-button v-else class="fr" @click="changeModel">切换模式</el-button>
    <div class="teachingPlanTag mar">
      <outerBox title="教案标签">
           <!-- <yes-tags @editTagList='editTagList' :tagsList.sync="tagsList" @delCanback='delCanback' /> -->

          <yes-tags @editTagList='editTagList' :id="list.id"  :tagsList.sync="tagsList" @delCanback='delCanback' />
          <el-button type="primary" size="medium" round @click="open">添加标签</el-button>
      </outerBox>
        </div>
    <div v-if="activeMode==='ONLINE'" class="lineWordMode ov">
      <!-- <div class="teachingPlanTag mar">
        <header>系统推荐标签</header>
        <yes-tags  :tagsList="sysList" />
         <el-button type="primary" size="medium" round @click="pushListFn">添加为标签</el-button>
      </div> -->
      <editor api-key="no-api-key" @input="putMsgFn" v-model="indexResList.content" />
    </div>
    <div v-else-if="activeMode==='MODULE'" class="standardMode ov">
       <div class="flex-box">
         <UploadPicFile class="fl" :options="{limit:1,'fileList':info.ModelFiles}"
          style="width:280px" type="file" @uploadSuccess="uploadTemplateSuccess" />
         <el-button size="mini" @click="autoParseFn">自动解析填充内容</el-button>
       </div>

      <div class="templateContentVOListBox ov">
        <div class="idxBox" :key="k" v-for="(idxItem,k) in templatePlatform.templateContentVOList">
          <h3 class="pad mar">{{idxItem.name}}</h3>
          <el-row :gutter="20" class="inpItemBox">
            <el-col class="inpBarList" :key="i" :span='11' v-for="(item, i ) in idxItem.item">
              <h4 class="pad mar">{{item.name}}</h4>
              <el-input v-if="item.name==='参考资料'" v-model="info.referVal" size="medium" resize="none" type="textarea" class="marTop" ></el-input>
              <el-input v-else size="medium" resize="none" type="textarea" class="marTop" v-model="item.content" />

            </el-col>
          </el-row>
          <div class="flex-fl marginT10" v-if="idxItem.name==='附件'">
            <UploadPicFile class="fl"
            :options="{limit:20,fileList:info.referFileUrl}"

             style="width:280px" type="file" @uploadSuccess="uploadSuccess" />
          </div>
        </div>
      </div>
    </div>
    <div class="footer-group margin30">
      <el-button type="success" @click="save">
        保存
      </el-button>
    </div>
    <tag-dialog :list="dialogObj" :tagsList="tagsList" :checkedVal.sync='checkedVal' :checkKeynote="checkKeynote"  :checkAbilityArr="checkAbilityArr" :ByPMapperList.sync="ByPMapperList"
      :importTagsList.sync="importTagsList" :dialogVisible.sync="dialogVisible" @changeImportCheckBox="changeImportCheckBox"
      :growthClassify="getClassfiyArr"
      @Callback="dialogCallback" />
    </div>

     <div class="IntorLessonDom fl"  >
        <IntorLesson v-if="$store.state.app.win >1300" :categorytagsList="categorytagsList"  @lookDetails="lookDetails" :span="24" />
        <template v-else>
        <el-button type="text" @click="drawerVisible = true" icon="el-icon-bottom-left" style="margin-left: 16px;">
          查看推荐
        </el-button>
       <el-drawer
         :visible.sync="drawerVisible"
         :before-close="handleClose"
         :destroy-on-close="true"
         >
         <IntorLesson :categorytagsList="categorytagsList"  @lookDetails="lookDetails" :span="24" />
       </el-drawer>
       </template>
       </div>

       <el-dialog
         title=""
         :close-on-click-modal="true"
         :visible.sync="isLookDetailsVisible"
          >
          <TeachDesignDetails v-if='isLookDetailsVisible' :id="lookDetailsId" ></TeachDesignDetails>
        </el-dialog>
  </div>
</template>
<script>
  import yesTags from './yesTags'
  import outerBox from '@/components/outerBox'
  import TagDialog from './tagDialog'
  import UploadPicFile from '@/components/UploadPicFile'
  import editor from '@/components/Tinymce/index';
  import IntorLesson from '../../list/designList'
  import TeachDesignDetails from '@/page/CreateResult/teachDesignDetails'
  import editClassTimeTabsMixin from './Mixin'
  import {
    saveResTeaching,getTemplate,autoParse
  } from '@/api/createResult'
  import { isJSONtest } from '@/utils'
  // import {
  //   findImportTagsList,
  //   findByPMapper,
  //   addContentTags
  // } from '@/api/tags'
  import {
    mapMutations
  } from 'vuex'
  export default {
    name: 'TeachingPlan',
    components: {
      yesTags,
       outerBox,
      editor,
      UploadPicFile,
      TagDialog,
      TeachDesignDetails,
      IntorLesson
    },
    mixins: [editClassTimeTabsMixin],
    data() {
      return {
        tagsList: [],
        hrefUrl:'',
        indexResList:{},
        info:{
          referFileUrl:[],//参考资料文件URl
          referVal:'',
          templateWocUrl:'',
          ModelFiles:[]
        },
        oldList:this.list,
        checkKeynote:[],
        checkAbilityArr:[],
        isLookDetailsVisible:false,
        lookDetailsId:'',
        drawerVisible:false,
        templatePlatform:{},
        hideHref:false,
        resType: 'TEACHING', //教案
        keynote: [],
        abilityArr: [],
        activeMode: '',
        ByPMapperList: [], //能力提升
        importTagsList: [],
        checkedVal: null,
        dialogVisible: false,
        content: '',
        improvementTagList: [],
        keyPointTagList: [],
        findStr:'``', //分割标准模式下 附件和  content text 的str
        referFileStr:',',//分割标准模式下 附件url的str
        sysList: [], //系统推荐标签
        dialogObj: {
          growthClassify: null,
          stageId: null,
          subjectId: null,
          tagsGroupEnum: null
        }
      }
    },
    created() {
     var that = this
     
     if(this.teachingDesignId){
        this.getTemplate()
         this.fetchData(this.list)
     }

    },
    watch:{
      list(val){
        //this.indexResList = val
        console.log("indexResList",val)
     this.fetchData(val)
      },
     activeMode(val){
       if(val==='ONLINE'){
        this.indexResList.content = this.list.content|| this.templatePlatform.contentHtml

       }else if(val==='MODULE'){
        this.indexResList.templateContentVOList = this.list.templateContentVOList || this.templatePlatform.templateContentVOList
        }
     }
    },

    mounted(){
      /*
       "tagList": [
                      {
                        "tagId": 1,
                        "tagName": "重点内容",
                        "tags": {
                          "additionalProp1": "string",
                          "additionalProp2": "string",
                          "additionalProp3": "string"
                        }
                      }
                    ],
      */
      if(this.list.tagList){
        if(this.list.tagList.length) this.getFindImportTags()
        //此处判断为：当编辑状态下有回选标签重点内容的时候 提前获取到所有的重点内容方便后面的修改标签
      }
    },
    props:{
    list:{
      type:[Object,Array],
    	default:()=>{
        return {}
         }
      },
    teachingDesignResId:{
      default:'',
    },
    },
    computed: {
      getClassfiyArr(){
        return this.$store.state.uploadLessonPlan.getClassfiyArr
      },
      categorytagsList(){
        let categorytagsList = this.$store.state.uploadLessonPlan.getClassfiyageListName || []
        //console.log("setClassifyCateList",categorytagsList)
        var newArr =[]

        this.tagsList.map(item=>{
          for(var k  in item){
             var arr = item[k]
              if(Array.isArray(arr)&&arr){
                arr.map(list=>{
                categorytagsList.push(list.tagsName)
                // newArr = categorytagsList.filter(items=>{
                //   return items!==list.tagsName
                // })
               })
              }
          }
        })
        return categorytagsList
      },
      contentOrModule() {
        let content = {}
        if (this.activeMode === 'MODULE') {
          //
         let  ContentVOList = this.templatePlatform.templateContentVOList
          if(this.info.referFileUrl){
            //替换 链接
           ContentVOList = this.toFilrFile(ContentVOList)
          }
         if(this.info.templateWocUrl){
             content.fileIds = this.info.templateWocUrl
         }
         //console.log("url",ContentVOList,urlStr)
         content.contentModule = JSON.stringify(ContentVOList)
         console.log("content",this.info,content)
        } else {
          content = {
            content: this.indexResList.content
          }
        }
        return content
      },
      teachingDesignId() {
        return this.$store.state.uploadLessonPlan.teachingPlanId
      },
      // templatePlatform() {
      //   this.info.templateContentVOList = this.$store.state.uploadLessonPlan.templatePlatform
      //   let templatePlatform = this.$store.state.uploadLessonPlan.templatePlatform
      //   return templatePlatform
      // }
    },
    methods: {
     fetchData(val){
       
       var that = this
       this.activeMode = val.editModel
       this.tagsList=this.idGetTagList(val.tagList)


       var list = val
       if(val.editModel){
         switch(list.editModel){
           case 'MODULE':
           this.templatePlatform.templateContentVOList = list.templateContentVOList
           list.templateContentVOList.map((items,i)=>{
              items.item.map((list,ind)=>{
                if(list.name==='参考资料'){
                 //list.content = that.info.referVal+ urlStr
                 let refer = list.content.split(that.findStr)
                 that.info.referVal = refer[0]
                 let referFileUrl = refer[1].split(that.referFileStr)
                  //回选附件文件 列表
                  referFileUrl.map(url=>{
                    //var url = item.url
                    if(url){
                       that.info.referFileUrl.push({url,name:url})
                    }
                  })
                }
              })
            })
           if(list.files){
             var files = isJSONtest(list.files)
             var filesList = typeof(files) ==='object'
             console.log('filesList',filesList)
             try{
               if(filesList){
                 for(var name in files.module){
                    this.info.ModelFiles.push({name,url:files.module[name]})
                   //
                 }
               }else{
                 this.info.ModelFiles.push({url:files,name:files})
               }

             }catch(err){
              console.log('model file',err)
             }
           }
           break;
           case 'ONLINE':
          // this.templatePlatform.content = list.content


           break;
           default:

         }

       }else{

       }
      this.indexResList.content = val.content|| this.templatePlatform.contentHtml
      //this.indexResList = val
        console.log('model content',val)
      // console.log("list",list,this.indexResList)
     },
     getTemplate(){
       getTemplate({
       teachingDesignId:this.$store.state.uploadLessonPlan.teachingPlanId,
       editToolType:'UEDITOR',
        resType: this.resType
      }).then((res)=>{
        if(res){
          this.templatePlatform = res.data
         // this.indexResList.content = res.data.contentHtml
        }
      })
      },
      putMsgFn(val) {
        //var hasList =  this.tagsList //已选择的
        // console.log("实打实",val)
        // if(){
        // }
      },
      lookDetails({id}){
        this.lookDetailsId = id
        this.isLookDetailsVisible = true
      },
      handleClose(done) {
         done();
      },
      open() {
        console.log(this.dialogVisible);
        this.dialogVisible = true;
        this.getFindImportTags()
      },
      autoParseFn(){
        autoParse({docUrl:this.info.templateWocUrl,templateId :this.templatePlatform.id}).then((res)=>{
          this.templatePlatform.templateContentVOList = res.data
         // that.info.templateWocUrl = that.info.filesUrl
        })
      },
      uploadTemplateSuccess({res,file,that}){
         this.info.templateWocUrl = that.info.filesUrl

         // that.info.fileList
      },
      uploadSuccess({res,file,that}){
       this.info.referFileUrl = that.info.fileList

      },
      changeModel() {
        this.activeMode = this.activeMode === 'ONLINE' ? 'MODULE' : 'ONLINE'
      },
      onClickMode(val) {
        this.dialogVisible = false
        this.activeMode = val
      },

      pushListFn() {
      },
      toFilrFile(arr){
        var that = this
        var urlStr = '';
        this.info.referFileUrl.map((itUrl,i,lisData)=>{
          urlStr += itUrl.url+(i<lisData.length-1?that.referFileStr:'')
        })
        urlStr = that.findStr + urlStr
       arr.map((items,i)=>{
        return  items.item.map((list,ind)=>{
            if(list.name==='参考资料'){
             return list.content = that.info.referVal+ urlStr
            }
          })
        })
        return arr
      },
      save() {
        var that = this
        console.log('this.tagsList', this.tagsList)
         const {improvementTagList,keyPointTagList} = this.getTagListSave(this.tagsList)
        let teachingDesignResId = this.teachingDesignResId
        let {teachingPlanId:teachingDesignId}  = this.$store.state.uploadLessonPlan
        let { id } = this.list
        let {typeEditTool}  = this.$store.state.uploadLessonPlan
        let {
          id: templatePlatformId
        } = this.templatePlatform
        let {
          activeMode: editModel,
          contentOrModule
        } = this
       // this.$set(this.info.template,'templateContentVOList',this.templatePlatform.templateContentVOList)
        var params = {
           editModel, //"ONLINE(在线编辑)",
          ...contentOrModule,
          //"contentModule": "模块化编辑内容",
          improvementTagList,
          id,
          keyPointTagList,
          teachingDesignId,
          teachingDesignResId,
          templatePlatformId,
          typeEditTool
        }

        //console.log("partamd",
        saveResTeaching(
          params
        ).then((res) => {
         this.$message.success('保存成功！')
        })
      },
    }
  }
</script>
<style lang="scss">
  .inpBarList {
    textarea {
      height: 300px;
    }
  }
   .IntorLessonDom{height: 650px;

   }
</style>
<style lang="scss" scoped>

  @media screen and (min-width: 1201px)  {
  .container {
    .IntorLessonDom{max-width:400px;background: white;}
      .wareList{
         //width:calc(100% - 400px)
      }
  }
  }
  @media  (min-width:1051px) and (max-width: 1200px)  {
  .container {
    .IntorLessonDom{background: white;}
      .wareList{
        // width:calc(100% - 200px)
      }
  }
  }

  .container {

     .IntorLessonDom{width:auto; background: white;height: 650px;}

    // padding: 24px;
    .modeBtn {
      .el-button {
        width: 320px;
        height: 80px;
        font-size: 14px;
        color: #000;
      }
    }
  }
</style>
